<template>
  <div class="page-container">
    <van-cell-group>
      <van-field
        ref="scanDom"
        v-model="scan"
        label=""
        label-width="130"
        left-icon="scan"
        style="background-color:lightYellow"
        placeholder="扫描配送单号/物品码"
        size="large"
        clearable
        border
        @keyup.enter.native="handleScanOver"
        @clear="handleScanClear"
        @click-left-icon="handleScanClear"
      />

      <van-field label="配送单号:" label-align="right" v-model="dist.busKey" size="mini" disabled />
      <van-field label="金额:" label-align="right" v-model="dist.amount" size="mini" disabled />
      <van-field label="科室:" label-align="right" v-model="dist.deptName"  size="mini" disabled />
      <van-field label="拣货人:" label-align="right" ref="pickerDOM" v-model="dist.picker"  size="mini" class="edit-field" right-icon="edit"/>
    </van-cell-group>
    <van-divider><span style="font-size:9px">配送单明细</span></van-divider>
    <div class="items-container">
      <van-collapse v-model="activeNames">
        <van-collapse-item
          v-for="distItem in distItems"
          :key="distItem.id"
          :name="distItem.id">
          <template #title>
            <div>
              <label>{{distItem.matrName}}</label>
            </div>
            <div>
              <span class="matr-spec">{{distItem.matrSpec}}</span>
            </div>
          </template>
          <template #value>
            <div class="value-container">
              <div><van-icon name="aim" /><label class="matr-qty">{{distItem.skuQty}}</label></div>
              <div><van-icon name="shopping-cart-o" /><label class="matr-qty">{{distItem.pickedSkuQty}}</label></div>
              <div>{{distItem.skuUnit}}</div>
            </div>
          </template>
          <template #right-icon>
            <div class="icon-container">
              <van-icon :name="getIcon(distItem,'name')" :class="getIcon(distItem,'class')" />
            </div>
          </template>
          <template>
            <div>
              <pick-item propTitleMode />
              <pick-item
                v-for="pickItem in getPickItems(distItem)"
                :key="pickItem.id"
                :value="pickItem"
                @remove-item="handleCancelPick(pickItem)"
              />
            </div>
          </template>
        </van-collapse-item>
      </van-collapse>
    </div>
    <div class="btn-container">
      <flow-buttons
        :propFlowKey="propFlowKey"
        :propDisabled="cpButtonDisable"
        plain
        @button-click="handleFlowButtonClick"
        style="width:100%" />
    </div>
  </div>
</template>

<script>
import FlowButtons from '@/components/FlowButtons.vue'
import PickItem from './PickItem.vue'

export default {
  data() {
    return {
      activeNames: [],
      scan: '',
      dist: {},
      distItems: [],
      pickItems: [],
      availableStatus: ['audit', 'picking', 'picked']
    }
  },
  props: {
    propFlowKey: String
  },
  mounted() {
    this.$refs.scanDom.focus()
  },
  computed: {
    cpButtonDisable() {
      return !this.dist.id
    }
  },
  methods: {
    getFlowNodeValue() {
      if (this.propFlowKey) {
        return this.propFlowKey.split(':')[1]
      }
    },
    getPickItems(distItem) {
      return this.pickItems.filter(item => item.distItemId == distItem.id)
    },
    getIcon(distItem, type) {
      if (distItem.skuQty == distItem.pickedSkuQty) {
        return type == 'name' ? 'passed' : 'passed'
      } else {
        return type == 'name' ? 'warning-o' : 'warning'
      }
    },
    getScanType(source) {
      const prefix1 = source.substring(0, 1)
      if (prefix1 == 'D') {
        return 'dist'
      } else if (prefix1 == 'F') {
        return 'rfid'
      } else  {
        return 'sn'
      }
    },
    setActiveName(uc, ucType) {
      const pickItem = this.pickItems.find(item => item[ucType] == uc)
      this.activeNames = [pickItem.distItemId]
    },
    handleScanClear(event) {
      this.scan = ''
    },
    handleScanOver() {
      if (window.isPDAScan()) this.scan = window.getPDAScan()
      if (!this.scan) return
      const scanType = this.getScanType(this.scan)
      if (scanType == 'dist') {
        this.handleReceiveDist(this.scan)
      } else {
        this.handleReceiveUC(this.scan, scanType)
      }
    },
    handleReceiveDist(distKey) {
      const params = { distKey }
      this.utils.loadShow()
      this.$ajax.get('/wm/dist/getDistByKey', { params }).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          if (!this.availableStatus.includes(response.data.dist.flowStatus)) {
            this.$dialog.alert({message: '该配送单未处于可拣货状态'})
            return
          }
          this.dist = response.data.dist
          this.distItems = response.data.distItems
          this.pickItems = response.data.pickItems
          if (!this.dist.picker) {
            const currentUser = this.$store.getters.currentUser.currentUser
            this.$set(this.dist, 'picker', currentUser.name)
          }
          this.resetScan()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    handleReceiveUC(uc, ucType) {
      if (!this.dist.id) {
        this.$notify.warning('请先扫描配送单号！')
        return
      }
      const params = {
        distId: this.dist.id,
        uniqueCode: uc
      }
      this.utils.loadShow()
      this.$ajax.post('/wm/dist/mobilePick', params).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          this.dist = response.data.dist
          this.distItems = response.data.distItems
          this.pickItems = response.data.pickItems
          if (!this.dist.picker) {
            const currentUser = this.$store.getters.currentUser.currentUser
            this.$set(this.dist, 'picker', currentUser.name)
          }
          this.setActiveName(uc, ucType)
          this.resetScan()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    handleCancelPick(pickItem) {
      const params = { ids: [pickItem.id] }
      this.utils.loadShow()
      this.$ajax.delete('/wm/dist/unpick', { data: params }).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          this.removePickItem(pickItem)
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    removePickItem(pickItem) {
      // delete pickItem
      this.pickItems.map((item, index) => {
        if (item.id == pickItem.id) {
          this.pickItems.splice(index, 1)
          return true
        }
      })
      // minus qty from distItem
      this.distItems.map(item => {
        if (item.id == pickItem.distItemId) {
          const qty = item.pickedSkuQty - pickItem.skuQty
          this.$set(item, 'pickedSkuQty', qty)
          return true
        }
      })
    },
    async handleFlowButtonClick(button) {
      const result = await this.$dialog.confirm({
        title: '流程确认',
        message: `确定要进行${button.title}操作吗？`
      })
      if (!result) return
      if (!this.dist.picker) {
        this.$notify.error('请设置拣货人！')
        this.$refs.pickerDOM.focus()
        return
      }
      const saveEntity = {
        id: this.dist.id,
        picker: this.dist.picker
      }
      const response = await this.$ajax.post('wm/dist/updatePicker', saveEntity)
      if (!response.success) {
        return
      }
      const flowKey = this.propFlowKey.split(':')[0]
      const params = {
        flowKey,
        buttonKey: button.code,
        busId: this.dist.id
      }
      this.utils.loadShow()
      this.$ajax.post('/wm/dist/flow_change', params).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          this.$notify.success(`${button.title}操作成功！`)
          this.clearForm()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    resetScan() {
      this.scan = ''
      this.$refs.scanDom.focus()
    },
    clearForm() {
      this.dist = {}
      this.distItems = []
      this.pickItems = []
      this.resetScan()
    }
  },
  components: {
    PickItem, FlowButtons
  }

}
</script>

<style lang="scss" scoped>
  .items-container {
    min-height: 80px;
  }
  .edit-field {
    background-color: lightblue;
  }
  .btn-container {
    padding:10px;
    flex-direction:column ;
    display: flex;
    justify-content: space-between;
  }
  .matr-spec {
    font-size:12px;
    color:gray;
  }
  .matr-qty {
    padding: 10px;
  }
  .value-container {
    height: 50px;
    display:flex;
    justify-content:space-around;
    align-items: center;
  }
  .icon-container {
    height: 50px;
    display:flex;
    justify-content:right;
    align-items: center;
  }
  .passed {
    color: green;
  }
  .warning {
    color: orangered;
  }
</style>
